package com.zjhcsoft.komm;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

@Name("authenticator")
public class Authenticator {

    @Logger
    Log log;
    @In
    Identity identity;
    @Out(required = false)
    User user;
    @In
    EntityManager entityManager;

    public boolean authenticate() {
        log.info("authenticating #0", identity.getUsername());
        List results = entityManager.createQuery("select u from User u where u.username=#{identity.username} and u.password=#{identity.password}").getResultList();

        if (results.size() == 0) {
            return false;
        } else {
            user = (User) results.get(0);
            if (user.getUsername().equals("chenlin")) {
                identity.addRole("admin");
            }
            if (user.getRoles() != null && user.getRoles().size() > 0) {
                for (Role role : user.getRoles()) {
                    if (role.getPermissions() != null && role.getPermissions().size() > 0) {
                        for (Permission permission : role.getPermissions()) {
                            ((ExtendedIdentity)identity).addPermission(permission.getTarget(), permission.getAction());
                        }
                    }
                }
            }
            return true;
        }

    }
}
